package com.sunshine.lnuplus.utils

import android.view.KeyEvent
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * Created by sunshine on 2020/4/4
 */

object WebViewUtils {
    fun initWebView(webView: WebView){
        webView.settings.apply {
            cacheMode = WebSettings.LOAD_DEFAULT
            domStorageEnabled = true
            javaScriptEnabled = true
            useWideViewPort = true //将图片调整到适合webview的大小
            loadWithOverviewMode = true // 缩放至屏幕的大小
            setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。
            builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
            displayZoomControls = false //隐藏原生的缩放控件
            cacheMode = WebSettings.LOAD_DEFAULT //关闭webview中缓存
            javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
            loadsImagesAutomatically = true //支持自动加载图片
            defaultTextEncodingName = "utf-8" //设置编码格式
            domStorageEnabled = true // 开启 DOM storage API 功能
            databaseEnabled = true //开启 database storage API 功能
            setAppCacheEnabled(true) //开启 Application Caches 功能
        }

        webView.webViewClient = WebViewClient()
        //返回键返回网页
        webView.setOnKeyListener(object : View.OnKeyListener {
            override fun onKey(v: View?, keyCode: Int, event: KeyEvent): Boolean {
                if (event.action === KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                        webView.goBack()
                        return true
                    }
                }
                return false
            }
        })
    }
}